package com.album.activity;

 import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Iterator;

import com.album.R;
import com.album.activity.base.BaseActivity;
import com.album.activity.base.BaseView;
import com.album.activity.page.Page;
import com.album.activity.page.PageManager;
import com.album.activity.pageView.CasualLookView;
import com.album.activity.pageView.MyFriendsView;
import com.album.activity.pageView.PicinfoView;
import com.album.common.Constants;
import com.album.service.UploadImageService;
import com.album.utils.CommonUtil;
import com.album.utils.Config;
import com.album.utils.MyLog; 

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.RadioGroup.OnCheckedChangeListener;
 

/**
 * @author Kadar.Li
 * @date 2011-7-4 
 * @version V1.0
 * @description VIPSHOP 主界面
 */
public class MainActivity extends BaseActivity implements OnClickListener{

	public static final int ACTIVITY_HONE = 0;
	public static final int ACTIVITY_BAG = 1;
	public static final int ACTIVITY_BRAND = 2;
	public static final int ACTIVITY_MORE = 3;
	
	public static final int ACTIVITY_DEFULT = 4; 

	private float mMoveBgSpeed = 0.3f;
	
	private int mContentMaxView = ACTIVITY_DEFULT + 1;
	private int mCurrentScreenItem = -1; 
	
	private ViewFlipper mMainViewFlipper;
	private ImageView mIconBgView;
	private ImageButton btnCamear,btnNitive,btnRefresh,btnCancel;
	private final int upload_image = 1;
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		MyLog.debug(getClass(), "============onCreate============");
		setContentView(R.layout.shell_main);  
		CommonUtil.initFolder(this);
		boolean network = CommonUtil.getPreferences(this, Constants.NETWORK_STATUS);
		MyLog.debug(getClass(), "********************************************network:"+network);
		if(network){
			MessageDialog.showToast(this, false, "网络正常");
		}
		initUI();
		initListener();
	}
	
	private Handler hanler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case upload_image:
				String filepath = msg.obj.toString();
				MyLog.debug(getClass(), filepath);
//				CommonUtil.deleteFile(filepath);
				showDialog(filepath);
				break;

			default:
				break;
			}
		}
	};
	private void showDialog(final String imagePath){
		AlertDialog dlg = new AlertDialog.Builder(this).setMessage("确定上传?")
		.setIcon(android.R.drawable.ic_input_delete)
		.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,int which) {
						try {
							dialog.dismiss();
							if(CommonUtil.isNetWorkActive(MainActivity.this)){
								Intent intent = new Intent(Config.UPLOAD_CAMERAIMAGE_ACTION);
								intent.setClass(MainActivity.this, UploadImageService.class);
								intent.putExtra(Config.CAMEAR_IMAGEPATH, imagePath);
								intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
								startService(intent);
							}else{
								MessageDialog.showToast(MainActivity.this, false, getResources().getString(R.string.int_error));
							}
						} catch (Exception e) { }
					}
				}).setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,int which) { dialog.dismiss(); }
				}).create();
		dlg.show();
	}
	public void initUI(){
//		LocalActivityManager m = getLocalActivityManager();
//		Intent intent = new Intent().setClass(this, DefultActivity.class); 
//		Window w = m.startActivity("tratat", intent); 
//		View v = w.getDecorView();  
		DefultActivity d = new DefultActivity(this);
		LinearLayout linearLayout = d.getView();
//		View v = 
		
		btnCamear = (ImageButton)findViewById(R.id.btn_camera);
		btnNitive = (ImageButton)findViewById(R.id.btn_nitive);
		btnRefresh = (ImageButton)findViewById(R.id.btn_refresh);
		btnCancel = (ImageButton)findViewById(R.id.btn_cancel);
		
		mMainViewFlipper = (ViewFlipper)findViewById(R.id.view_bodyview);
		mMainViewFlipper.addView(linearLayout);
		mMainViewFlipper.setDisplayedChild(0);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent it = new Intent();
		switch (v.getId()) {
		case R.id.btn_camera:
			doTakePhoto();
			break;
		case R.id.btn_nitive:
			it.setClass(this, nitiveManagerActivity.class);
			startActivityForResult(it, nitive_back);
			break;
		case R.id.btn_refresh:
			refreshData();
			break;
		case R.id.btn_cancel:
			//destroyAll();
			backToView();
			break;
		default:
			break;
		}
	}
	 
	private final int nitive_back = 111;
	  /** 
	    * 拍照获取图片 
	    *  
	    */  
	    protected void doTakePhoto() {  
	        try {   
	            // Launch camera to take photo for selected contact   
	        	PhotoFileName = getPhotoFileName();
	        	mCurrentPhotoFile = new File(CommonUtil.getSdCardDir()+Config.public_image, PhotoFileName);// 给新照的照片文件命名  
	            Intent intent = getTakePickIntent(mCurrentPhotoFile);  
	            startActivityForResult(intent, CAMERA_WITH_DATA);  
	        } catch (ActivityNotFoundException e) {  
	            Toast.makeText(this, "错误",  Toast.LENGTH_LONG).show();  
	        }  
	    }
	/*用来标识请求照相功能的activity*/  
	private static final int CAMERA_WITH_DATA = 3023; 
	/*用来标识请求gallery的activity*/  
	private static final int PHOTO_PICKED_WITH_DATA = 3021;  
	private File mCurrentPhotoFile;
	
//	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    	MyLog.debug(getClass(), "requestCode:"+requestCode+" resultCode:"+resultCode); 
        switch (requestCode) {  
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的  
            	if(data!=null){ 
//                    final Bitmap photo = data.getParcelableExtra("data");  
            		Message msg = new Message();
            		msg.what = upload_image;
            		msg.obj = filePath;
            		hanler.sendMessage(msg);
            	}else{
                	MyLog.debug(getClass(), "delete..."); 
            		CommonUtil.deleteFile(filePath);
            	} 
                break;  
            }  
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片  
            	MyLog.debug(getClass(), "CAMERA_WITH_DATA...");
            	MyLog.debug(getClass(), "PhotoFileName:"+PhotoFileName);
            	if(PhotoFileName!=null){
                	mCurrentPhotoFile = new File(CommonUtil.getSdCardDir()+Config.public_image, PhotoFileName);// 给新照的照片文件命名
                	filePath = mCurrentPhotoFile.getPath();
                	MyLog.debug(getClass(), "path:"+filePath);
                    doCropPhoto(mCurrentPhotoFile);  
            	}
                break;  
            }  
            case nitive_back: 
            	if(resultCode == RESULT_OK){
                	MyLog.debug(getClass(), ".......RESULT_OK.......");
                	if(mMainViewFlipper!=null){
                    	MyLog.debug(getClass(), ".......mMainViewFlipper not null......."); 
//                    	mMainViewFlipper.setDisplayedChild(0);
                	}
            	}
            	break;
           
        }  
        
//    	CommonUtil.saveFileBitmap(b,Config.public_image, System.currentTimeMillis() + ".png");
	}
	/** 
	    * 用当前时间给取得的图片命名 
	    *  
	    */  
	private String getPhotoFileName() {  
	     return System.currentTimeMillis() + ".png";  
	}  
	private String PhotoFileName,filePath;
	
	private Intent getTakePickIntent(File f) {  
	     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);  
	     intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));  
    return intent;  
 } 
	
    protected void doCropPhoto(File f) {  
        try {  
            // 启动gallery去剪辑这个照片  
            final Intent intent = getCropImageIntent(Uri.fromFile(f));  
            startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);  
        } catch (Exception e) {  
            Toast.makeText(this, "修剪出错" ,Toast.LENGTH_LONG).show();  
        }  
    }  
    /**  
     * Constructs an intent for image cropping. 调用图片剪辑程序  
     */  
     public static Intent getCropImageIntent(Uri photoUri) {  
         Intent intent = new Intent("com.android.camera.action.CROP");  
         intent.setDataAndType(photoUri, "image/*");  
         intent.putExtra("crop", "true");  
         intent.putExtra("aspectX", 1);  
         intent.putExtra("aspectY", 1);  
         intent.putExtra("outputX", 80);  
         intent.putExtra("outputY", 80);  
         intent.putExtra("return-data", true);  
         return intent;  
     }  
	public void initListener(){
		btnCamear.setOnClickListener(this);
		btnNitive.setOnClickListener(this);
		btnRefresh.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { 
			AlertDialog.Builder builder = new AlertDialog.Builder(this); 
			builder.setTitle("提示");
			builder.setMessage(R.string.label_exitTip) 
			       .setCancelable(false) 
			       .setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() { 
			           public void onClick(DialogInterface dialog, int id) { 
//			       		CommonUtil.setUserInfo("", "", MainActivity.this); 
			       		MainActivity.this.finish(); 	
			           } 
			       }) 
			       .setNegativeButton(R.string.label_cancel, new DialogInterface.OnClickListener() { 
			           public void onClick(DialogInterface dialog, int id) { 
			                dialog.cancel(); 
			           } 
			       }); 
			builder.show();
			return true;
		}
		return true;
	} 
	
	public void onIntoScreen() {
		// TODO Auto-generated method stub
		
	}

	public void onLeaveScreen() {
		// TODO Auto-generated method stub
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		try {
			ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
			activityManager.restartPackage(getPackageName());
			android.os.Process.killProcess(android.os.Process.myPid());
			clearBitmapListThread();
			System.exit(0);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		super.onDestroy();
	} 
	private void refreshData(){
		MyLog.info(getClass(), "refreshData");
		try {
			if (SetstateManager.refreshMap != null && !SetstateManager.refreshMap.isEmpty()) {
				Iterator it = SetstateManager.refreshMap.keySet().iterator();
				PageManager manager = null;
				Class c = null;
				while (it.hasNext()) {
					c = (Class) it.next();
					manager = SetstateManager.refreshMap.get(c);
					MyLog.info(getClass(), "c=" + c + " manager=" + manager);
				}
				MyLog.info(getClass(), "refresh:" + c);
					if (manager != null){
						manager.destroyPage(c);
						manager.activePage(c, null);
					}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//返回
	private void backToView (){
		MyLog.info(getClass(), "back to");
		try {
			if (SetstateManager.backtoStateMap != null && !SetstateManager.backtoStateMap.isEmpty()) {
				Iterator it = SetstateManager.backtoStateMap.keySet().iterator();
				PageManager manager = null;
				Class c = null;
				while (it.hasNext()) {
					c = (Class) it.next();
					manager = SetstateManager.backtoStateMap.get(c);
					MyLog.info(getClass(), "c=" + c + " manager=" + manager);
				}
				MyLog.info(getClass(), "back to:" + c);
					if (manager != null)
						manager.activePage(c, null);
					if(c == MyFriendsView.class){
						
					}
					
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	} 
	public void destroyAll(){
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(this); 
			builder.setTitle("提示");
			builder.setMessage(R.string.label_exitTip) 
			       .setCancelable(false) 
			       .setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() { 
			           public void onClick(DialogInterface dialog, int id) { 
			       		MainActivity.this.finish();
			           } 
			       }) 
			       .setNegativeButton(R.string.label_cancel, new DialogInterface.OnClickListener() { 
			           public void onClick(DialogInterface dialog, int id) { 
			                dialog.cancel(); 
			           } 
			       });  
			builder.show();
		} catch (Exception e) { }
	} 
}